package com.lsh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lsh.dao.CatalogDao;
import com.lsh.dao.CourseDao;
import com.lsh.dao.QuestionDao;
import com.lsh.dao.TagDao;
import com.lsh.entity.QueryPageBean;
import com.lsh.pojo.Catalog;
import com.lsh.pojo.Course;
import com.lsh.pojo.Tag;
import com.lsh.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CatalogDao catalogDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private QuestionDao questionDao;

    @Override
    public void addCourse(Course course) {
        courseDao.addCourse(course);
    }

    @Override
    public PageInfo<Course> findCourse(QueryPageBean queryPageBean) {
        //开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Course> list = courseDao.findCourse(queryPageBean);
        PageInfo<Course> page = new PageInfo(list);
        return page;
    }
    @Override
    public void delete(Integer id) {
        //首先看被依赖的表是否有数据
        long index;
        //1.二级目录t_catalog
         index = catalogDao.selectByCouresId(id);
         if(index > 0){
             throw new RuntimeException("有关联的二级目录，无法删除");
         }
        //2.标签 t_tag
         index = tagDao.selectByCouresId(id);
        if(index > 0){
            throw new RuntimeException("有关联的标签，无法删除");
        }
        //3.题目
        index = questionDao.selectByCouresId(id);
        if(index > 0){
            throw new RuntimeException("有关联的题目，无法删除");
        }
        courseDao.delete(id);
    }

    @Override
    public void update(Course course) {
        courseDao.update(course);
    }

    @Override
    public List<Course> findAll(Integer status) {
        List<Course> courseList = courseDao.findAll(status);
        for (Course course : courseList) {
            //查询二级目录
            List<Catalog> catalogList = catalogDao.findByCourseId(course.getId());
            course.setCatalogList(catalogList);
            //查询标签
            List<Tag> tagList = tagDao.findByCourseId(course.getId());
            course.setTagList(tagList);
        }
        return courseList;
    }
}
